package com.wellink.viewswitcherdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    public static final int NUMBER_PRE_SCREEN = 12;
    public static int screenNo = -1;
    public static int screenCount;

    ViewSwitcher switcher;
    Button btnPrev;
    Button btnNext;
    SwitcherAdapter adapter;
    List<ItemData> dataList = new ArrayList<ItemData>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        switcher = findViewById(R.id.switcher);
        btnPrev = findViewById(R.id.btnPre);
        btnNext = findViewById(R.id.btnNext);

        switcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                return MainActivity.this.getLayoutInflater().inflate(R.layout.group_layout,null);
            }
        });

        for(int i=0;i<40;i++){
            ItemData data = new ItemData("item_"+i,R.mipmap.ic_launcher);
            dataList.add(data);
        }

        screenCount = dataList.size() %NUMBER_PRE_SCREEN == 0? dataList.size()/ NUMBER_PRE_SCREEN:dataList.size()%NUMBER_PRE_SCREEN+1;
        adapter = new SwitcherAdapter(this,dataList);
        btnPrev.setOnClickListener(this);
        btnNext.setOnClickListener(this);

        next();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnPre:
                prev();
                break;
            case R.id.btnNext:
                next();
                break;
                default: break;
        }
    }

    void next(){
        if(screenNo <screenCount -1){
            screenNo ++;
            switcher.setInAnimation(this,R.anim.slide_in_right);
            switcher.setOutAnimation(this,R.anim.slide_out_left);
            ((GridView)switcher.getNextView()).setAdapter(adapter);
            switcher.showNext();
        }
    }

    void prev(){
        if(screenNo >0){
            screenNo --;
            switcher.setInAnimation(this,android.R.anim.slide_in_left);
            switcher.setOutAnimation(this,android.R.anim.slide_out_right);

            ((GridView)switcher.getNextView()).setAdapter(adapter);
            switcher.showPrevious();
        }
    }
}
